import React, {useEffect, useState} from "react";
import styles from "./index.style";
import {Image, TouchableHighlight, View} from "react-native";
import {Ionicons} from "@expo/vector-icons";
import {router} from "expo-router";
import {toQueryString} from "@/utils/url-utils";
import {useChatMessageActions, useChatMessageState} from "@/hooks/chat/chat-message";
import {generateVideoThumbnail} from "@/utils/file-utils";

interface AutoSizeVideoProps {
    uri: string;
    thumbnail: string;
    messageId: string;
    setShow: (value: ((prevState: boolean) => boolean) | boolean) => void;
}

export default function AutoSizeVideo({
                                          uri,
                                          thumbnail : initialThumbnail,
                                          messageId,
                                          setShow,
                                      }: AutoSizeVideoProps) {
    const {enableMultipleSelect} = useChatMessageState();
    const {addSelectedMessage} = useChatMessageActions();
    const {updateMessage} = useChatMessageActions();
    const [thumbnail, setThumbnail] = useState(initialThumbnail);

    const checkOrReGenerateThumbnail = async () => {
        const GenerateResult = await generateVideoThumbnail(messageId,uri)
        if (GenerateResult.regenerated) {
            await updateMessage({
                messageId,
                content: {
                    url: uri,
                    thumbnail: GenerateResult.uri
                }
            });
            const newThumbnail = GenerateResult.uri;
            setThumbnail(newThumbnail);
        }

    };

    useEffect(() => {
        checkOrReGenerateThumbnail();
    }, []);

    return (
        <View
            style={{
                width: 200,
                height: 200,
            }}
        >
            <TouchableHighlight
                style={styles.placeholder}
                onPress={() => {
                    enableMultipleSelect
                        ? addSelectedMessage(messageId)
                        : router.navigate(
                            `media/video-preview?${toQueryString({
                                uri,
                            })}`
                        );
                }}
                onLongPress={() => setShow(true)}
            >
                <>
                    <Image
                        source={{uri: thumbnail}}
                        style={[{borderRadius: 8}, {width: 200, height: 200}]}
                        resizeMode="cover"
                        progressiveRenderingEnabled={true} // 启用渐进式渲染
                    />
                    <Ionicons
                        name="play-circle-outline"
                        size={64}
                        color="white"
                        style={styles.playingIcon}
                    />
                </>
            </TouchableHighlight>
        </View>
    );
}
